package com.hua.nailcampus.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import java.util.Date;

/**
 * @author chenjianhua
 */
public class JwtHelper {

    private static long tokenExpiration = 30*60*1000;
    private static final String Token_Sign_Key = "nailCampus";


    /**
     * 根据userId与phone生成token字符串
     * @param userId
     * @param phone
     * @return
     */
    public static String createToken(Integer userId, String phone) {
        String token = Jwts.builder()
                .setSubject("nailCampus-USER")

                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))

                .claim("userId", userId)
                .claim("phone", phone)

                .signWith(SignatureAlgorithm.HS512, Token_Sign_Key)

                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static Integer getUserId(String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(Token_Sign_Key).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId;
    }

    public static String getPhone(String token) {
        if(StringUtils.isEmpty(token)){
            return "";
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(Token_Sign_Key).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("phone");
    }

    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1, "admin");
        System.out.println(token);

        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getPhone(token));
    }
}
